import './index.scss'
import {ExclamationCircleOutlined, PlusOutlined, UploadOutlined} from '@ant-design/icons';
import LineEcharts from "../../components/Echarts/LineEchart";
import {Button, message, Modal, Upload, UploadFile, UploadProps} from "antd";
import React, {useEffect, useState} from "react";
import {BASE_UPLOAD_FILE} from "../../axios";
import {beforeUpload, getBase64} from "../../util";
import {RcFile} from "antd/es/upload";
import WangEdit from "../../components/WangEdit";
import {ArticleDataType, LiteratureDataType, MetaType, RegionType} from "../../util/publicType";
import {regionDetail, relationArticleList, relationLiteratureList, updateRegion} from "../../api";
import {useParams} from "react-router-dom";
import {AxiosResponse} from "axios";
import RegionTable from "../../components/RegionTable";

// 区域
const Region = () => {
    // 上传的附件
    const [videoList, setVideoList] = useState<UploadFile[]>([]);
    // 预览控制
    const [previewOpen, setPreviewOpen] = useState(false);
    // 预览地址
    const [previewImage, setPreviewImage] = useState('');
    // 预览标题
    const [previewTitle, setPreviewTitle] = useState('');
    // 上传图片列表
    const [imageList, setImageList] = useState<UploadFile[]>([]);
    // 编辑的内容
    const [html, setHtml] = useState<string>("");
    // 区域数据
    const [regionData, setRegionData] = useState<RegionType>({
        id: '',
        name: '',
        videos: [],
        images: [],
        category_id: '',
        content: ''
    });
    // 当前区域字典id
    const {id} = useParams();
    // 文献分页
    const [literaturePage, setLiteraturePage] = useState<number>(1);
    // 文章未关联分页
    const [relationPage, setRelationPage] = useState<number>(1);
    // 当前未关联页数
    const [relationSize, setRelationSize] = useState<number>(15);
    // 关联项数据
    const [relationData, setRelationData] = useState<LiteratureDataType[] | ArticleDataType[]>([]);
    // 关联弹窗
    const [relationOpen, setRelationOpen] = useState<boolean>(false);
    // 关联类型标题
    const [title, setTitle] = useState<string>("关联文献");
    // 是否为关联操作
    const [isRelation, setIsRelation] = useState<boolean>(false);
    // 文献未关联搜索字段
    const [literatureName, setLiteratureName] = useState<string | null>(null);
    // 文章未关联搜索字段
    const [articleName, setArticleName] = useState<string | null>(null);
    // 当前文献页数
    const [literatureSize, setLiteratureSize] = useState<number>(15);
    // 文章分页
    const [articlePage, setArticlePage] = useState<number>(1);
    // 当前页数
    const [articleSize, setArticleSize] = useState<number>(15);
    // 文献数据
    const [literatureData, setLiteratureData] = useState<LiteratureDataType[]>([]);
    // 文章数据
    const [articleData, setArticleData] = useState<ArticleDataType[]>([]);

    // 文献分页数据
    const [literatureMeta, setLiteratureMeta] = useState<MetaType>({
        currentPage: 1,
        lastPage: 1,
        perSize: 1,
        total: 1
    });
    // 文章分页数据
    const [articleMeta, setArticleMeta] = useState<MetaType>({
        currentPage: 1,
        lastPage: 1,
        perSize: 1,
        total: 1
    });
    // 关联选择数据
    const [relationMeta, setRelationMeta] = useState<MetaType>({
        currentPage: 1,
        lastPage: 1,
        perSize: 1,
        total: 1
    });


    // 加载文件
    const setFileData = (data: Array<{ id: string, path: string, type: string }>) => {
        return data.map(v => {
            return {
                uid: v?.id,
                status: 'done',
                name: v?.type,
                url: v?.path
            };
        })
    }

    // 区域详情
    const getDetail = () => {
        regionDetail((id as string)).then((r: AxiosResponse) => {
            const data: RegionType = r.data.data.data;
            let videosList: any[] = [];
            let imagesList: any[] = [];
            videosList = setFileData(data.videos);
            imagesList = setFileData(data.images);
            setVideoList(videosList);
            setImageList(imagesList)
            setRegionData(data);
            setHtml(data?.content ? data?.content : "");
        }, err => message.error(err))
    }

    // 字段重新赋值
    const setRqData = (data: ArticleDataType[] | LiteratureDataType[]): ArticleDataType[] | LiteratureDataType[] => {
        return data.map(v => {
            return {
                ...v,
                key: v.id,
                dictName: v.dict.name
            }
        }) as (ArticleDataType[] | LiteratureDataType[])
    }

    // 请求文献
    const getLiteratureData = (page: number, size: number, name: string | null = null, regionId: number | null = null) => {
        relationLiteratureList((id as string), page, size, name, regionId).then((r: AxiosResponse) => {
            let {data, meta} = r.data.data;
            if (regionId !== 0) {
                setLiteratureMeta(meta);
                setLiteratureData(setRqData(data) as LiteratureDataType[]);
            } else {
                setRelationMeta(meta);
                setRelationData(setRqData(data) as LiteratureDataType[]);
            }
        }, err => message.error(err))
    }

    // 请求文章
    const getArticleData = (page: number, size: number, name: string | null = null, regionId: number | null = null) => {
        relationArticleList((id as string), page, size, name, regionId).then((r: AxiosResponse) => {
            let {data, meta} = r.data.data;
            if (regionId !== 0) {
                setArticleMeta(meta);
                setArticleData(setRqData(data) as ArticleDataType[]);
            } else {
                setRelationMeta(meta);
                setRelationData(setRqData(data) as ArticleDataType[]);
            }

        }, err => message.error(err))
    }

    // 区域切换时
    useEffect(() => {
        setArticleName(null);
        setLiteratureName(null);
        setLiteraturePage(1);
        setLiteratureSize(15);
        setArticlePage(1);
        setArticleSize(15);
        setVideoList([]);
        setImageList([]);
        getArticleData(articlePage, articleSize, articleName);
        getLiteratureData(literaturePage, literatureSize, literatureName);
        getDetail();
    }, [id])

    // 上传按钮
    const uploadButton = (
        <div>
            <PlusOutlined/>
            <div style={{marginTop: 8}}>上传图片</div>
        </div>
    );

    // 上传视频
    const props: UploadProps = {
        name: 'file',
        action: BASE_UPLOAD_FILE,
        onChange({fileList: newFileList}) {
            setVideoList(newFileList)
        },
    };

    // 预览
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };

    // 文件i变化
    const handleChange: UploadProps['onChange'] = ({fileList: newFileList}) => {
        setImageList(newFileList);
    }

    // 获取文件id
    const getFileId = (data: any[]) => {
        return data.map(v => {
            return v?.response?.data?.data?.id ? v?.response?.data?.data?.id : v?.uid;
        })
    }
    // 保存
    const saveCLick = () => {
        let videos: string[];
        let images: string[];
        videos = getFileId(videoList);
        images = getFileId(imageList);
        updateRegion(regionData.id, {images, videos, content: html}).then(() => {
            getDetail()
            message.success("更新成功");
        }, err => message.error(err))
    }

    // 关联点击
    const relationClick = (v: string) => {
        setRelationOpen(true);
        setIsRelation(true);
        if (v === "文献") {
            setTitle("关联文献")
            getLiteratureData(relationPage, relationSize, literatureName, 0);
        } else {
            setTitle("关联文章")
            getArticleData(relationPage, relationSize, literatureName, 0)
        }
    }

    return (
        <div className="region-box" style={{padding: "30px 0"}}>
            <div className="region_left">
                <div>
                    <div>
                        <p>访问数据</p>
                        <ExclamationCircleOutlined/>
                    </div>
                    <div>
                        <LineEcharts />
                    </div>
                    <p>日访问量</p>
                </div>
                <div>
                    <div>
                        <h1>视频（最多9个，限制mp4）</h1>
                        {/*清除数据，保留状态*/}
                        <Upload {...props} accept=".mp4" fileList={videoList} onRemove={() => setVideoList([])}>
                            {
                                videoList.length > 8 ? null : <Button icon={<UploadOutlined/>}>上传视频文件</Button>
                            }
                        </Upload>
                    </div>
                    <div>
                        <h1>封面（最多9张）</h1>
                        <Upload
                            accept="image/*"
                            action={BASE_UPLOAD_FILE}
                            listType="picture-card"
                            fileList={imageList}
                            beforeUpload={beforeUpload}
                            onPreview={handlePreview}
                            onChange={handleChange}
                        >
                            {imageList.length > 8 ? null : uploadButton}
                        </Upload>
                    </div>
                </div>
            </div>
            <div className="region_right">
                <div>
                    <h1>地方简介</h1>
                    <WangEdit html={html} setHtml={setHtml} borderColor="#1890ff"/>
                    <div style={{margin: "30px auto", width: "60px"}}>
                        <Button type="primary" onClick={saveCLick}>保存</Button>
                    </div>
                </div>
                <div className="region-right-title">
                    <div>
                        <h1>文献管理</h1>
                        <p onClick={() => relationClick("文献")}>添加关联文献</p>
                    </div>
                    <RegionTable meta={literatureMeta}
                                 isArticle={false}
                                 dictId={regionData.id}
                                 setPage={setLiteraturePage}
                                 setSize={setLiteratureSize}
                                 getData={getLiteratureData}
                                 data={literatureData}/>
                </div>
                <div className="region-right-title">
                    <div>
                        <h1>文章管理</h1>
                        <p onClick={() => relationClick("文章")}>添加关联文章</p>
                    </div>
                    <RegionTable meta={articleMeta}
                                 dictId={regionData.id}
                                 setPage={setArticlePage}
                                 setSize={setArticleSize}
                                 getData={getArticleData}
                                 data={articleData}/>
                </div>
            </div>
            {/*预览*/}
            <Modal open={previewOpen} title={previewTitle} footer={null}
                   onCancel={() => setPreviewOpen(false)}>
                <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
            {/* 添加关联文献 */}
            <Modal open={relationOpen}
                   title={title}
                   footer={null}
                   onCancel={() => {
                       setIsRelation(false);
                       setRelationOpen(false);
                       setRelationPage(1);
                       setRelationSize(15);
                   }}
            >
                <RegionTable meta={relationMeta}
                             isRelation={isRelation}
                             dictId={id as string}
                             title={title}
                             setPage={setRelationPage}
                             setSize={setRelationSize}
                             getData={getArticleData}
                             data={relationData}/>
            </Modal>
        </div>
    )
}

export default Region;